package com.zhq.okhttp;

import android.content.Context;

import com.zhq.okhttp.subscribe.DownImageResponseListener;
import com.zhq.okhttp.subscribe.HttpRequestListener;
import com.zhq.okhttp.subscribe.NetWorkErrorThrowable;
import com.zhq.okhttp.subscribe.ProgressSubscriber;
import com.zhq.okhttp.subscribe.SubscriberImageThread;
import com.zhq.okhttp.subscribe.SubscriberUIThread;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;


/**
 * Created by Administrator on 2016/9/14.
 * <p/>
 * HttpGET、Post网络请求封装工具类
 */
public class ApiHttpUtils extends RetrofitUtils {
    private static ApiHttpUtils netWork;



    public static ApiHttpUtils getInstance() {
        if (netWork == null) {
            synchronized (ApiHttpUtils.class) {
                if (netWork == null) {
                    netWork = new ApiHttpUtils();
                }
            }
        }
        return netWork;
    }

    /***
     * HttpGet/Post 请求
     * @param listener:监听者
     * @param observable   :观察着对象,内含Retrofit的url表达式
     **/
    public void subscribeHttpRequest(HttpRequestListener listener, final Observable<ResponseBody> observable) {
        observable
                .retryWhen(new NetWorkErrorThrowable())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())//回调到主线程
                .subscribe(new SubscriberUIThread(listener));
    }

    /***
     * HttpGet/Post 请求
     * @param listener:监听者
     * @param observable   :观察着对象,内含Retrofit的url表达式
     **/
    public void subscribeProgressRequest(Context mContext, String message, HttpRequestListener listener, Observable<ResponseBody> observable) {
        observable.retryWhen(new NetWorkErrorThrowable())
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())//回调到主线程
                .subscribe(new ProgressSubscriber.Builder(mContext).setHttpRequestOnListener(listener).setMessage(message).build());
    }

    /***
     * HttpGet请求
     * @param listener:监听者
     * @param observable   :观察着对象,内含Retrofit的url表达式
     **/
    public void subscribeGetImage(DownImageResponseListener listener, Observable<ResponseBody> observable) {
        observable
                .subscribeOn(Schedulers.io())
                .subscribeOn(Schedulers.newThread())//子线程访问网络
                .observeOn(AndroidSchedulers.mainThread())//回调到主线程
                .subscribe(new SubscriberImageThread(listener));
    }


}





